<template>
  <j-modal
    :confirmLoading="confirmLoading"
    :ok=false
    :okButtonProps="{ props: {disabled: disableSubmit} }"
    :title="title"
    :visible="visible"
    :width="1200"
    cancelText="关闭"
    switchFullscreen
    @cancel="handleCancel"
    @ok="handleOk">
    <a-spin :spinning="confirmLoading">
      <div class="top-box">
        <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 12px">
          <div style="text-align: right;flex: 1">经销商：</div>
          <cn-select-cust :value="model.custName"
                          :disabled="disableSubmit||title=='编辑'"
                          :inputs="true"
                          :multiple="false"
                          :returnName="true"
                          :buttons="false"
                          searchIcon="search"
                          :queryParams="{ permflag: 'servuce_ment_save_impl'}"
                          selectButtonText="选择"
                          style="width: 188px"
                          @select="handleLeaderName">
          </cn-select-cust>
        </div>
        <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 12px">
          <div style="text-align: right;flex: 1">目标年月：</div>
          <a-month-picker :disabled="disableSubmit||title=='编辑'" valueFormat="YYYY-MM" v-model="model.month"
                          placeholder="请选择" @change="selectMonth">
          </a-month-picker>
        </div>
        <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 12px">
          <div style="text-align: right;flex: 1">形象覆盖次数：</div>
          <a-input :value="model.imageCoverCount" :disabled="true" style="width:180px"></a-input>
        </div>
        <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 12px">
          <div style="text-align: right;flex: 1">S：</div>
          <a-input :value="model.coverCounts" :disabled="true" style="width:180px"></a-input>
        </div>
        <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 12px">
          <div style="text-align: right;flex: 1">A：</div>
          <a-input :value="model.coverCounta" :disabled="true" style="width:180px"></a-input>
        </div>
        <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 12px">
          <div style="text-align: right;flex: 1">B：</div>
          <a-input :value="model.coverCountb" :disabled="true" style="width:180px"></a-input>
        </div>
        <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 12px">
          <div style="text-align: right;flex: 1">C：</div>
          <a-input :value="model.coverCountc" :disabled="true" style="width:180px"></a-input>
        </div>
        <div style="display: flex;align-items: center;justify-content: space-between;margin-bottom: 12px">
          <div style="text-align: right;flex: 1">D：</div>
          <a-input :value="model.coverCountd" :disabled="true" style="width:180px"></a-input>
        </div>
        <div style="display: flex;align-items: center;justify-content: flex-end;margin-bottom: 12px;z-index:999">
          <a-button type="primary" @click="handleAverage" style="margin-right: 12px">均摊目标</a-button>
          <a-button type="primary" @click="handleResult">重置</a-button>
        </div>
      </div>
      <div>
        <a-table
          bordered
          size="small"
          row-key="key"
          :columns="columns"
          :dataSource="model.targetChildrenList"
          :pagination="false"
          :scroll="{x:600,y:500 }"
          @edit-disabled="editDisabledEvent"
        >
          <template slot="imageCoverCount" slot-scope="text, record,index">
            <a-input-number :min="0" v-model="record.imageCoverCount" style="width:100%"></a-input-number>
          </template>
          <template slot="coverCounts" slot-scope="text, record,index">
            <a-input-number :min="0" v-model="record.coverCounts" style="width:100%"></a-input-number>
          </template>
          <template slot="coverCounta" slot-scope="text, record,index">
            <a-input-number :min="0" v-model="record.coverCounta" style="width:100%"></a-input-number>
          </template>
          <template slot="coverCountb" slot-scope="text, record,index">
            <a-input-number :min="0" v-model="record.coverCountb" style="width:100%"></a-input-number>
          </template>
          <template slot="coverCountc" slot-scope="text, record,index">
            <a-input-number :min="0" v-model="record.coverCountc" style="width:100%"></a-input-number>
          </template>
          <template slot="coverCountd" slot-scope="text, record,index">
            <a-input-number :min="0" v-model="record.coverCountd" style="width:100%"></a-input-number>
          </template>
          <template slot="action" slot-scope="text, record, index">
            <a @click="handleDelete(index)">删除</a>
          </template>
        </a-table>
      </div>
    </a-spin>
  </j-modal>
</template>

<script>
import { getAction, httpAction, postAction } from '@/api/manage'
import { queryDepartTreeList, queryIdTree } from '@/api/api'
import { pick } from 'lodash'
import ATextarea from 'ant-design-vue/es/input/TextArea'
import JSelectUser from '@comp/cn-select-popup/JSelectUser'
import CnSelectCust from '@comp/cn-select-popup/CnSelectCust'

export default {
  name: 'SysDepartModal',
  components: { ATextarea, JSelectUser, CnSelectCust },
  data() {
    return {
      listUrl: '/cnUserController/getPageList',
      departTree: [],
      orgTypeData: [],
      phoneWarning: '',
      dataSources: [{}],
      title: '操作',
      isAll: false,
      seen: false,
      visible: false,
      condition: false,
      disableSubmit: false,
      model: {},
      menuhidden: false,
      menuusing: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 }
      },
      columns: [
        {
          title: '用户账号',
          align: 'center',
          dataIndex: 'userName',
        },
        {
          title: '用户姓名',
          align: 'center',
          dataIndex: 'realName',
        },
        // {
        //   title: '职位',
        //   align: 'center',
        //   dataIndex: 'positionName',
        // },
        {
          title: '目标年月',
          align: 'center',
          dataIndex: 'month',
        },
        {
          title: '巡店目标次数',
          align: 'center',
          dataIndex: 'shopTargetCount',
        },
        {
          title: '培训目标次数',
          align: 'center',
          dataIndex: 'trainTargetCount',
        },
        {
          title: '形象覆盖次数',
          align: 'center',
          dataIndex: 'imageCoverCount',
          scopedSlots: { customRender: 'imageCoverCount' }
        },
        {
          title: 'S',
          align: 'center',
          dataIndex: 'coverCounts',
          scopedSlots: { customRender: 'coverCounts' }
        },
        {
          title: 'A',
          align: 'center',
          dataIndex: 'coverCounta',
          scopedSlots: { customRender: 'coverCounta' }
        },
        {
          title: 'B',
          align: 'center',
          dataIndex: 'coverCountb',
          scopedSlots: { customRender: 'coverCountb' }
        },
        {
          title: 'C',
          align: 'center',
          dataIndex: 'coverCountc',
          scopedSlots: { customRender: 'coverCountc' }
        },
        {
          title: 'D',
          align: 'center',
          dataIndex: 'coverCountd',
          scopedSlots: { customRender: 'coverCountd' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          align: 'center',
          width: 80,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        realName: { rules: [{ required: true, message: '' }] },
        checkPeriod: { rules: [{ required: true, message: '' }] },
        visitPlanCustNum: { rules: [{ required: true, message: '' }] },
        helpPlanCustNum: { rules: [{ required: true, message: '' }] },
      },
      url: {
        add: window._CONFIG['domianSfaURL'] + '/sales/target/saveOrUpdate',
        target: window._CONFIG['domianSfaURL'] + '/sales/target/getInfoByMonthAndUserName',
      },
      dictDisabled: true
    }
  },
  created() {
    this.loadTreeData(0)
  },
  methods: {
    // 用户选择
    async handleLeaderName(list) {
      if (list.length) {
        if (this.model.month) {
          this.confirmLoading = true
          let res = await postAction(this.url.target, {
            month: this.model.month,
            custCode: list[0].custCode,
            custName: list[0].custName,
            departCode: list[0].departCode,
            departName: list[0].departName,
          })
          if (res.success) {
            delete res.result.id
            this.model = Object.assign({}, res.result, {
              custCode: list[0].custCode,
              custName: list[0].custName,
              departCode: list[0].departCode,
              departName: list[0].departName,
              month: this.model.month
            })
          } else {
            this.$message.error(res.message)
          }
          this.confirmLoading = false
        } else {
          this.model = Object.assign({}, {
            custCode: list[0].custCode,
            custName: list[0].custName,
            departCode: list[0].departCode,
            departName: list[0].departName,
            month: this.model.month
          })
        }
      } else {
        this.model = {}
      }

    },
    initDictConfig() {

    },
    handleResult() {
      let {
        targetChildrenList = []
      } = this.model
      this.model.targetChildrenList = targetChildrenList.map(item => {
        item.imageCoverCount = 0
        item.coverCounts = 0
        item.coverCounta = 0
        item.coverCountb = 0
        item.coverCountc = 0
        item.coverCountd = 0
        return item
      })
    },

    handleAverage() {
      let {
        imageCoverCount,
        coverCounts,
        coverCounta,
        coverCountb,
        coverCountc,
        coverCountd,
        targetChildrenList = []
      } = this.model
      let coverCount = Math.ceil(imageCoverCount / targetChildrenList.length)
      let s = Math.ceil(coverCounts / targetChildrenList.length)
      let a = Math.ceil(coverCounta / targetChildrenList.length)
      let b = Math.ceil(coverCountb / targetChildrenList.length)
      let c = Math.ceil(coverCountc / targetChildrenList.length)
      let d = Math.ceil(coverCountd / targetChildrenList.length)
      this.model.targetChildrenList = targetChildrenList.map(item => {
        item.imageCoverCount = coverCount
        item.coverCounts = s
        item.coverCounta = a
        item.coverCountb = b
        item.coverCountc = c
        item.coverCountd = d
        return item
      })
    },
    handleDelete(index) {
      this.model.targetChildrenList.splice(index, 1)
    },
    // 选择月份
    async selectMonth(e) {
      if (e && this.model.custCode) {
        this.confirmLoading = true
        let res = await postAction(this.url.target, { month: e, custCode: this.model.custCode })
        if (res.success) {
          delete res.result.id
          this.$set(this, 'model', Object.assign({}, res.result, {
            custCode: this.model.custCode,
            custName: this.model.custName,
            departCode: this.model.departCode,
            departName: this.model.departName,
            month: e
          }))
        } else {
          this.$message.error(res.message)
          this.model = Object.assign({}, {
            custCode: this.model.custCode,
            custName: this.model.custName,
            departCode: this.model.departCode,
            departName: this.model.departName,
            month: e
          })
        }
        this.confirmLoading = false
      } else {
        this.model = Object.assign({}, {
          custCode: this.model.custCode,
          custName: this.model.custName,
          departCode: this.model.departCode,
          departName: this.model.departName,
          month: e
        })
      }
    },

    loadTreeData(orgCode) {
      var that = this
      // if (this.isAll) {
      queryDepartTreeList().then((res) => {
        if (res.success) {
          that.departTree = []
          for (let i = 0; i < res.result.length; i++) {
            let temp = res.result[i]
            temp.key = temp.orgCode
            this.departTree.push(temp)
          }
        }
      })
    },
    // handleSelectTag(value) {
    //   if (value == 2) {
    //     this.seen = false
    //   } else {
    //     this.seen = true
    //   }
    // },

    add() {
      this.edit({})
    },

    edit(record) {
      console.log(record)
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.model.targetChildrenList = record.details || []
      this.visible = true
    },
    close() {
      this.$emit('close')
      this.disableSubmit = false
      this.visible = false
    },

    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)
          formData.details = formData.targetChildrenList
          console.log(this.form)
          //时间格式化
          console.log(formData)
          httpAction(this.url.add, formData, 'post').then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })

        }
      })
    },
    handleCancel() {
      this.close()
    },
    // // 用户选择
    // handleLeaderName(list) {
    //   console.log(list)
    //   if (list.length) {
    //     this.form.setFieldsValue({ userName: list[0].userName })
    //     this.form.setFieldsValue({ positionName: list[0].positionName })
    //     this.form.setFieldsValue({ positionCode: list[0].positionCode })
    //   } else {
    //     this.form.setFieldsValue({ userName: '' })
    //     this.form.setFieldsValue({ positionName: '' })
    //     this.form.setFieldsValue({ positionCode: '' })
    //   }
    // }
  }
}
</script>

<style scoped lang="less">
.top-box {
  display: flex;
  flex-wrap: wrap;

  div {
    width: 25%;
  }
}

</style>
